import { ApplicationController } from "../support/application-controller";
import axios from 'axios'

export default class extends ApplicationController {
  initialize () {
    var guaguakaContent = document.getElementById('scratch_result');
    var myCanvas = document.getElementById('scratch');
    var ctx = myCanvas.getContext('2d');
    var mouseDown = false;
    var mouseIn = false;
    var width = myCanvas.width;
    var height = myCanvas.height;
    var offsetLeft = myCanvas.offsetLeft;
    var offsetTop = myCanvas.offsetTop;
    // 先将canvas画上灰色蒙层
    ctx.fillStyle = '#c5c3c4';
    ctx.fillRect(0, 0, width, height);
    ctx.font = "50px bold 黑体";
    ctx.fillStyle = '#6d6d6d';
    ctx.textAlign='center';
    ctx.textBaseline='middle';
    ctx.fillText('刮开有奖', width / 2, height / 2, 100);
    // 此行非常重要，设置再绘制时的显示模式
    ctx.globalCompositeOperation="destination-out";
    var prizeList = [];
    axios.get('/api/v1/scratch_card_awards.json').then((response) => {
      if (response.data.result) {
        prizeList = response.data.data;
        console.info(prizeList);
        // 随机算是否得奖
        var prize = prizeList[Math.floor(Math.random()*2)];
        guaguakaContent.innerText = prize.name;
        this.data.set("sid", prize.id);
        myCanvas.addEventListener('mousedown', (e) => {
          e.preventDefault();
          mouseDown = true;
        })
        myCanvas.addEventListener('touchstart', (e) => {
          e.preventDefault();
          mouseDown = true;
        })
        myCanvas.addEventListener('mouseup', (e) => {
          e.preventDefault();
          mouseDown = false;
        })
        myCanvas.addEventListener('mouseover', (e) => {
          e.preventDefault();
          mouseIn = true;
        })
        myCanvas.addEventListener('mouseout', (e) => {
          e.preventDefault();
          mouseIn = false;
          if (this.data.get("scratched") === "true") {
            console.info(this.data.get("scratched"));
            axios.post('/api/v1/user_scratch_card_awards.json', {
              user_id: this.data.get("uid"),
              order_id: this.data.get("oid"),
              scratch_card_award_id: this.data.get("sid")
            }).then((response) => {
              console.info(response)
            })
          }
        })
        myCanvas.addEventListener('touchend', (e) => {
          e.preventDefault();
          mouseDown = false;
          if (this.data.get("scratched") === "true") {
            console.info(this.data.get("scratched"));
            axios.post('/api/v1/user_scratch_card_awards.json', {
              user_id: this.data.get("uid"),
              order_id: this.data.get("oid"),
              scratch_card_award_id: this.data.get("sid")
            }).then((response) => {
              console.info(response)
            })
          }
        })
        myCanvas.addEventListener('mousemove', (e) => {
          if (this.data.get("scratched") === "false") {
            var completed = 0;
            var data = ctx.getImageData(0, 0, 120, 40).data;
            var total = data.length / 4;
            var i;
            e.preventDefault();
            if(!mouseDown || !mouseIn){
              return;
            }
            ctx.beginPath();
            ctx.arc(e.offsetX, e.offsetY, 10, 0, Math.PI *2)
            ctx.fill();
            // 刮的数量到一半时，打印完成刮奖，4个数记录1个相素的rgba值，判断a值为0的超过一半即可
            for (i = 3; i < data.length; i += 4) {
              if (data[i] === 0) {
                completed += 1;
              }
            }
            if (completed > total / 2) {
              myCanvas.style.display = "none";
              this.data.set("scratched", true);
            }
          }
        })
        myCanvas.addEventListener('touchmove', (e) => {
          if (this.data.get("scratched") === "false") {
            var rect = e.target.getBoundingClientRect();
            var completed = 0;
            var data = ctx.getImageData(0, 0, 120, 40).data;
            var total = data.length / 4;
            var i;
            e.preventDefault();
            if (!mouseDown) {
              return;
            }
            ctx.beginPath();
            ctx.arc(e.targetTouches[0].pageX - rect.left, e.targetTouches[0].pageY - rect.top, 20, 0, Math.PI *2)
            ctx.fill();
            // 刮的数量到一半时，打印完成刮奖，4个数记录1个相素的rgba值，判断a值为0的超过一半即可
            for (i = 3; i < data.length; i += 4) {
              if (data[i] === 0) {
                completed += 1;
              }
            }
            if (completed > total / 2) {
              myCanvas.style.display = "none";
              this.data.set("scratched", true);
            }
          }
        })
        
      } else {
        alert(response.data.message);
      }
    }).catch(function (error) {
      if (error.response) {
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      }
    });
  }
}